package session

import (
	"gitee.com/Cookie_XiaoD/video_server/api/dbops"
	"gitee.com/Cookie_XiaoD/video_server/api/defs"
	"gitee.com/Cookie_XiaoD/video_server/utils"
	"sync"
	"time"
	"log"
)

var sessionMap *sync.Map

func init() {
	sessionMap = &sync.Map{}
}

//从数据库加载session
func LoadSessionFromDB() {
	result, err := dbops.RetrieveAllSessions()
	if err != nil {
		return
	}
	result.Range(func(key, value interface{}) bool {
		v, ok := value.(*defs.SimpleSession)
		if ok {
			sessionMap.Store(key, v)
		}
		return true
	})
}

//根据username生成sessionid
func GenerateNewSessionId(un string) (string, error) {
	uuid, err := utils.NewUUID()
	if err != nil {
		return "", err
	}
	ct := nowInMilli()
	ttl := ct + 30*60*1000

	log.Println("准备插入session")
	if err = dbops.InsertSeesion(uuid, ttl, un); err != nil {
		return "", err
	}
	ss := &defs.SimpleSession{
		Username: un,
		TTL:      ttl,
	}
	sessionMap.Store(uuid, ss)

	return uuid, nil
}

//session是否过期
func IsSessionExpired(sid string) (string, bool) {
	ss,ok:=sessionMap.Load(sid)
	if !ok{
		return "",true
	}
	session:=ss.(*defs.SimpleSession)
	if session.TTL>=nowInMilli(){
		return session.Username,false
	}
	//过期，删除数据库中的session
	if err:=delExpiredSession(sid);err==nil{
		return "",true
	}
	//删除数据库失败依然标记为过期
	//TODO:这里是否合理待验证
	return "", true
}

func delExpiredSession(sid string) error{
	err:=dbops.DelSession(sid)
	if err!=nil{
		return err
	}
	//从数据库中删除成功，删除缓存
	sessionMap.Delete(sid)
	return nil
}




func nowInMilli() int64{
	return time.Now().UnixNano()/1000000
}